import { login, logout, getUserInfo } from '@/api/user'
import { setToken, getToken, routersConfigAssembly } from '@/libs/util'
import { menuRefactoring } from '@/libs/business_util'
import { findAllMenu } from '@/api/menu/list'
import _ from 'lodash'

export default {
  state: {
    username: '',
    userId: '',
    avatorImgPath: '',
    token: getToken(),
    access: '',
    menuList: []
  },
  mutations: {
    setAvator (state, avatorPath) {
      state.avatorImgPath = avatorPath
    },
    setUserId (state, id) {
      state.userId = id
    },
    setusername (state, name) {
      state.username = name
    },
    setAccess (state, access) {
      state.access = access
    },
    setMenu (state, menuList) {
      state.menuList = menuList
    },
    setToken (state, token) {
      state.token = token
      setToken(token)
    }
  },
  actions: {
    // 登录
    handleLogin ({ commit }, {username, password}) {
      return new Promise((resolve, reject) => {
        login({
          username,
          password
        }).then(res => {
          const data = res
          commit('setToken', data.access_token)
          resolve()
        }).catch(err => {
          reject(err)
        })
      })
    },
    // 退出登录
    handleLogOut ({ state, commit }) {
      return new Promise((resolve, reject) => {
        logout(state.token).then(() => {
          commit('setToken', '')
          commit('setAccess', [])
          resolve()
        }).catch(err => {
          reject(err)
        })
        // 如果你的退出登录无需请求接口，则可以直接使用下面三行代码而无需使用logout调用接口
        // commit('setToken', '')
        // commit('setAccess', [])
        // resolve()
      })
    },
    // 获取用户相关信息
    getUserInfo ({ state, commit }) {
      return new Promise((resolve, reject) => {
        getUserInfo(state.token).then(res => {
          const data = res.user
          commit('setAvator', 'https://avatars0.githubusercontent.com/u/20942571?s=460&v=4')
          commit('setusername', data.username)
          commit('setUserId', data.userId)
          commit('setAccess', res.authorities)
          commit('setMenu', res.menuList)
          resolve(data)
        }).catch(err => {
          reject(err)
        })
      })
    },
    getRoutersConfig ({ state, commit }) {
      return findAllMenu().then((routersData) => {
        //  console.log('获取到用户菜单：' + JSON.stringify(routersData.data))
        // 把菜单列表转为框架标准路由JSON格式
        debugger
        let newRoutersData = menuRefactoring(routersData.list, 0)
        //  console.log("转换路由："+JSON.stringify(newRoutersData))
        let routersConfig = _.cloneDeep(newRoutersData)
        let newRoutersConfigObj = routersConfigAssembly(routersConfig)
        commit('setRoutersConfig', { newRouters: newRoutersConfigObj, routersData: newRoutersData })
        return newRoutersConfigObj
      })
    }
  }
}
